package application;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import jeopardy.common.Utils;
import jeopardy.common.protocol.useraccount.UserAccountConsts;
import jeopardy.common.protocol.useraccount.UserAccountRequest;
import jeopardy.common.protocol.useraccount.UserAccountUtils;

// import jeopardy.server.ServerConsts;

/**
 * FXML Controller class
 * 
 * @author Angie
 */
public class LoginScreenController implements Initializable, ControlledScreen {

	private int authenticated;

	// Variables for reading input from the form
	@FXML
	private Text authMessage;
	@FXML
	private TextField userIDField;
	@FXML
	private TextField passwordField;
	
	public String userName;
	public char[] passWord;
	public String rtPassword = "letmein123";

	ScreensController myController;

	/**
	 * Initializes the controller class.
	 */
	@Override
	public void initialize(URL url, ResourceBundle rb) {
		// TODO
	}

	public void setScreenParent(ScreensController screenParent) {
		myController = screenParent;
	}

	/*
	 * @FXML private void goToLoginScreen(ActionEvent event){
	 * myController.setScreen(ScreensFramework.LoginScreenID); }
	 */
	// Process button action
	@FXML
	private void processLoginScreen(ActionEvent event) {
		passWord = getPassword();
		userName = getUserName();

		// if (isEmpty(passWord) || isEmpty(userName) || (userName.length() > 11)) {
		if (!UserAccountUtils.validatePasswordString(passWord) || !UserAccountUtils.validateUserString(userName)) {

			authMessage.setText("Either the User Name or the Password is invalid\n User Name should be at least 8 characters long");
		} else {
			try {
				validateUser();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if (authenticated == 1) {
		/*
		* Uncomment and transition to a new screen based on registration.
		*/			
			myController.setScreen(ScreensFramework.PreGameScreenID);
			// myController.setScreen(ScreensFramework.GameScreenID);

		}

	}

	// Create SSL Connection to server
	public int validateUser() throws UnknownHostException, IOException {
		byte[] returnCode = new byte[UserAccountConsts.USERACCOUNT_MAX_RES_LEN];
		
		try {
			SSLSocketFactory sslsocketfactory = ClientConsts.createSSLFactory();
			SSLSocket socket = (SSLSocket) sslsocketfactory.createSocket(
					ClientConsts.SERVER_IP, ClientConsts.SERVER_PORT);
			
			/* 
			 * Try to connect to the server - on success attempt to 
			   authenticate the user, otherwise display message
			*/
			if(socket.isConnected()) {
				System.out.println("Communication with server established - authenticating");
				authMessage.setText("Communication with server established - authenticating");

				
				UserAccountRequest uar = UserAccountUtils
						.createUserAuthRequest(userName, passWord);
				
				// System.out.println("User name to send is: "+userName);
				// System.out.println("Password to send is: "+passWord);
				
				socket.getOutputStream().write(
						UserAccountUtils.reqToNetworkMsg(uar));
				socket.getOutputStream().flush();
				
				/*
				System.out.println(socket.getInputStream().read());
				PrintWriter out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream()));
				*/
				
				// Read the response from the server and then parse it
				Utils.readBytes(socket.getInputStream(), returnCode);
				
				// Check the return code for authentication
				// Check the return code for authentication
				if(UserAccountUtils.parseUserAccountResponse(returnCode) ==  ClientConsts.authSuccess) {
					System.out.println("Authentication successful");
					authMessage.setText("Authentication successful");
					authenticated = 1;
				}
				else {
					System.out.println("Authentication failure");
					authMessage.setText("Authentication failure");
				}
			}
			else {
				System.out.println("Failed to connect to the server");
				authMessage.setText("Unable to communicate with server");
			}
			
			
		} catch (Exception exception) {
			exception.printStackTrace();
			System.out.println("Failed to communicate to the server");
			authMessage.setText("Failed to communicate with server");
		}
		return 0;
	}

	// Get user name
	public String getUserName() {
		if (userIDField == null || isEmpty(userIDField.getText())) {
			return "";
		}
		return userIDField.getText();
	}

	// Get password
	public char[] getPassword() {
		if (passwordField == null || isEmpty(passwordField.getText())) {
			return null;
		}
		return passwordField.getText().toCharArray();
	}

	private boolean isEmpty(String s) {
		return s == null || s.trim().isEmpty();
	}
	
}
